<?php

function authorized($userId) {
    session_start();
    if (!empty($_SESSION['user_id'])) {
        if ($userId == $_SESSION['user_id']) {
            return true;
        }
    }
    return false;
}

function getDbLink() {
    $link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
    mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $link);
    mysql_select_db('simplydecide', $link) or die('Cannot select the DB');
    return $link;
}

//function getDbLink(){
//			$link = mysql_connect('simplydecide.db.11240480.hostedresource.com','simplydecide','simplyDecide#8') or die('Cannot connect to the DB');
//			mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $link);
//			mysql_select_db('simplydecide',$link) or die('Cannot select the DB');
//			return $link;
//}

function closeDbLink($link) {
    @mysql_close($link);
}

function begin($link) {
    mysql_query("BEGIN", $link);
}

function commit($link) {
    mysql_query("COMMIT", $link);
}

function rollback($link) {
    mysql_query("ROLLBACK", $link);
}

function getCount($tableName, $link) {
    $query = "select count(*) as total from `" . $tableName . "`";
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $result = mysql_fetch_array($result);
    return intval($result['total']);
}

function getTopTopics($link) {
    $query = "select question_id,question from oc_question where who_can_see = 0 order by recent_activity_date DESC LIMIT 5";
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            $records[] = $record;
        }
    }
    return $records;
}

function getTopDecisions($link) {
    $query = "select t1.question_id, t2.question, count(*) as question_count from oc_voting as t1, oc_question as t2 where t1.question_id in (select oc_decision.question_id from oc_decision,oc_question where oc_question.who_can_see = 0 and oc_decision.question_id = oc_question.question_id) and t1.question_id = t2.question_id group by question_id order by question_count DESC LIMIT 5";
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            $records[] = $record;
        }
    }
    return $records;
}

function getDecision($questionId, $link) {
    $query = "select * from oc_decision where question_id = " . intval($questionId);
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            return array('decision_made' => true, 'answer_id' => $record['answer_id']);
        }
    } else {
        return array('decision_made' => false, 'answer_id' => -1);
    }
}

function getQuestionDetails($questionid, $link) {    
    $query1 = "SELECT `question_id`, `question` , `recent_activity_date`,`customer_id`, `category_id` FROM `oc_question` WHERE `question_id` = " . intval($questionid);
    $question_info = mysql_query($query1, $link) or die('Errant query:  ' . $query1);
    $question_info = mysql_fetch_array($question_info);
    $query = "SELECT a1.answer_id,a1.answer, COUNT(a2.answer_id)AS votes " .
            "FROM (SELECT answer_id, answer from  `oc_answer` WHERE question_id = " . intval($questionid) .
            ")  AS a1 LEFT JOIN (SELECT `vote_id`,`answer_id` FROM `oc_voting` WHERE `question_id` = " . intval($questionid) .
            ") AS a2 on a1.answer_id = a2.answer_id GROUP BY a1.answer_id";
    $answers = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($answers)) {
        while ($record = mysql_fetch_assoc($answers)) {
            $records[] = $record;
        }
    }
    $queryCustomer = "SELECT `firstname`,`lastname` FROM  `oc_customer` WHERE `customer_id`=" . $question_info['customer_id'];
    $customerDetails = mysql_query($queryCustomer, $link) or die('Errant query:  ' . $queryCustomer);
    $customer_first_name = "";
    $customer_last_name = "";

    if (mysql_num_rows($customerDetails)) {
        while ($record = mysql_fetch_assoc($customerDetails)) {
            $customer_first_name = $record['firstname'];
            $customer_last_name = $record['lastname'];
        }
    }

    $queryCategory = "SELECT `name` FROM `oc_category_description` WHERE `category_id` =" . $question_info['category_id'];
    $categoryDetails = mysql_query($queryCategory, $link) or die('Errant query:  ' . $queryCategory);
    $category_name = "";

    if (mysql_num_rows($customerDetails)) {
        while ($record = mysql_fetch_assoc($categoryDetails)) {
            $category_name = $record['name'];
        }
    }

    header('Content-type: application/json');
    return array('question_id' => $question_info['question_id'],
        'question' => $question_info['question'],
        'category' => array('id' => $question_info['category_id'],
            'name' => $category_name),
        'postedBy' => array('id' => $question_info['customer_id'],
            'firstName' => $customer_first_name,
            'lastName' => $customer_last_name),
        'postedOn' => $question_info['recent_activity_date'],
        'answers' => $records);
}

function questionDetails($questionId, $link) {
    $query = "SELECT a1.question_id,a1.question,a1.answer_id,a1.answer, COUNT(a2.answer_id)AS votes FROM" .
            "(SELECT t1.question_id,t1.question,t2.answer_id,t2.answer from " .
            "(SELECT `question_id`, `question` FROM `oc_question` " .
            "WHERE `question_id` = " . intval($questionId) . ") AS t1 " .
            "INNER JOIN `oc_answer` AS t2 on  t1.question_id = " . intval($questionId) .
            " AND t1.question_id = t2.question_id) AS a1 left join " .
            "(SELECT `vote_id`,`answer_id` FROM `oc_voting` WHERE `question_id` = " . intval($questionId) .
            ") AS a2 on a1.answer_id = a2.answer_id GROUP BY a2.answer_id";

    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array('questionId' => "", 'options' => array());
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            $records['questionId'] = $record['question_id'];
            $records['question'] = $record['question'];
            $records['options'][] = array('answerId' => $record['answer_id'],
                'answer' => $record['answer'],
                'votes' => $record['votes']);
        }
    }
    header('Content-type: application/json');
    return $records;
}

function getDecisionCount($userid, $link) {
    $query1 = "SELECT COUNT(DISTINCT  `question_id` ,  `answer_id`) AS `count`  FROM  `oc_voting` WHERE  `voter_id` =" . intval($userid);
    $result1 = mysql_query($query1, $link);
    $result1array = mysql_fetch_assoc($result1);
    $totalVotes = $result1array["count"];
    //Get the questions that have been answered out of the previous list
    $query2 = "SELECT  COUNT(*) AS `count` FROM (SELECT DISTINCT  `question_id` ,  `answer_id`  FROM  `oc_voting` WHERE  `voter_id` =" . intval($userid) . ") AS t1 INNER JOIN oc_decision AS t2 ON t1.question_id = t2.question_id";
    $result2 = mysql_query($query2, $link);
    $result2array = mysql_fetch_assoc($result2);
    $closedQuestions = $result2array["count"];
    //Get the questions that have been answered correctly
    $query3 = "SELECT  COUNT(*) AS `count` FROM (SELECT DISTINCT  `question_id` ,  `answer_id`  FROM  `oc_voting` WHERE  `voter_id` =" . intval($userid) . ") AS t1 INNER JOIN oc_decision AS t2 ON t1.question_id = t2.question_id AND t1.answer_id = t2.answer_id";
    $result3 = mysql_query($query3, $link);
    $result3array = mysql_fetch_assoc($result3);
    $hitQuestions = $result3array["count"];
    return (array('decisionPending' => intval($totalVotes) - intval($closedQuestions), 'decisionAccepted' => intval($hitQuestions), 'decisionRejected' => intval($closedQuestions) - intval($hitQuestions)));
}

function fetchUserData($userid, $link) {
    $query1 = "SELECT firstname, lastname,gender,image FROM oc_customer WHERE customer_id =" . intval($userid);
    $result1 = mysql_query($query1, $link);
    $user_details = mysql_fetch_assoc($result1);
    $query2 = "SELECT COUNT(voter_id) AS votes FROM oc_voting WHERE voter_id =" . intval($userid);
    $result2 = mysql_query($query2, $link);
    $result2array = mysql_fetch_assoc($result2);
    $votes = $result2array["votes"];
    $query3 = "SELECT COUNT(from_friend_id) AS friends FROM oc_friend_circle WHERE from_friend_id = " . intval($userid) . " AND approve= 1 ";
    $result3 = mysql_query($query3, $link);
    $result3array = mysql_fetch_assoc($result3);
    $friends = $result3array["friends"];
    $query4 = "SELECT COUNT(DISTINCT category_id) AS favourites FROM oc_customer_to_category WHERE customer_id = " . intval($userid);
    $result4 = mysql_query($query4, $link);
    $result4array = mysql_fetch_assoc($result4);
    $favourites = $result4array["favourites"];

    return (array(
        'user' => $user_details,
        'votes' => $votes,
        'friends' => $friends,
        'favourites' => $favourites
    ));
}

function fetchUserQuestions($userid, $link) {
    $query = "SELECT question_id,question FROM oc_question WHERE customer_id = " . intval($userid) . " ORDER BY recent_activity_date DESC";
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            $records[] = $record;
        }
    }
    $latest_posts = $records;
    $query = "SELECT question_id,question FROM oc_question WHERE question_id IN (SELECT question_id FROM oc_voting WHERE voter_id = " . intval($userid) . " ORDER BY vote_date DESC)";
    $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
    $records = array();
    if (mysql_num_rows($result)) {
        while ($record = mysql_fetch_assoc($result)) {
            $records[] = $record;
        }
    }
    $latest_votes = $records;
    return (array(
        'recent_questions' => $latest_posts,
        'recent_votes' => $latest_votes
    ));
}

//$service_code = isset($_POST['servicecode']) ? intval($_POST['servicecode']) : 0;
//
//switch ($service_code ){
//case 0:
//    echo json_encode(array('result' => 'failed'));
//    break;
//case 1:
//	//signup
//	/*emailid(username),oc_customer
//	*password,oc_customer
//	*name,oc_customer , oc_address
//	*lastname,oc_customer, oc_address
//	*gender, oc_customer
//	*country,
//	*region or state
//	*/
//	$link = getDbLink();
//	$login = isset($_POST['login']) ? $_POST['login'] : "";
//	$query = "select `customer_id` from `oc_customer` where`email`='".$login."'";
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	if(mysql_num_rows($result)){
//		echo json_encode(array('result' => 'failure','message' => 'already existing email id'));
//		break;
//	}
//
//	$password = isset($_POST['password']) ? $_POST['password'] : "";
//	$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
//	$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
//	$gender = isset($_POST['lastname']) ? $_POST['lastname'] : "";
//	$countrycode = isset($_POST['countrycode']) ? $_POST['countrycode'] : 0;
//	$regioncode = isset($_POST['regioncode']) ? $_POST['regioncode'] : 0;
//
//	try {
//		begin($link);
//		$salt = substr(md5(uniqid(rand(), true)), 0, 9);
//		$encodedpassword = sha1($salt.sha1($salt.sha1($password)));
//		$query1 = "insert into `oc_customer` (`firstname`, `lastname`, `gender`,`email`,`password`, `salt`,`date_added`) values ('". $firstname ."', '". $lastname."', '". $gender."','".$login."','".$encodedpassword."','".$salt."',now());" ;
//		$result = mysql_query($query1,$link);
//		$query3 = "SELECT `customer_id` FROM  `oc_customer` WHERE `email`='".$login."'";
//		$result = mysql_query($query3,$link);
//		$resultarray =  mysql_fetch_assoc($result);
//		$assignedId = $resultarray['customer_id'];
//		$query2 = "insert into `oc_address` (`customer_id`,`firstname`, `lastname`,`country_id`,`zone_id`) values ('".$assignedId."','". $firstname ."', '". $lastname."', ". intval($countrycode).",".intval($regioncode).")" ;
//		//echo $query2;
//		$result = mysql_query($query2,$link);
//		commit($link);
//		echo json_encode(array('result' => 'success',"id" =>$assignedId));
//	} catch (Exception $e) {
//		rollback($link);
//		echo json_encode(array('result' => 'failure'));
//	}
//	closeDbLink($link);
//    break;
//case 2:
//	//login
//    $link = getDbLink();
//	$login = isset($_POST['login']) ? $_POST['login'] : 0;
//	$password = isset($_POST['password']) ? $_POST['password'] : 0;
//	$query = "SELECT `customer_id`,`password`,`salt` FROM  `oc_customer` WHERE `email`='".$login."'";
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	header('Content-type: application/json');
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			$userid = $record['customer_id'];
//			if($record['password'] == (sha1($record['salt'].sha1($record['salt'].sha1($password))))){
//				echo json_encode(array('result' => 'passed', 'userid' => $userid));
//			}else{
//				echo json_encode(array('result' => 'failed', 'userid' => -1, 'pwd' => $record['password'], 'entered' =>(sha1($record['salt'].sha1($record['salt'].sha1('test'))))));
//			}
//		}
//	}else{
//			echo json_encode(array('result' => 'failed', 'userid' => -1));
//	}
//	closeDbLink($link);
//    break;
//case 3:
//	//get all categories
//	$link = getDbLink();
//	$query = "select t1.category_id, t2.name, t1.image from `oc_category` AS t1 INNER JOIN `oc_category_description` AS t2 WHERE t1.category_id = t2.category_id" ;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			//var_dump($record);
//			$records[] = array('record'=>$record);
//		}
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//case 4:
//	//search Questions by keyword
//	$link = getDbLink();
//	$keys = isset($_POST['key']) ? $_POST['key'] : "";
//	$keyword_tokens = explode(',', $keys);
//	//var_dump($keyword_tokens);
//	$query = "select t1.question_id,t1.question,t1.customer_id,t1.hide_my_name,t2.answer_id,t2.answer FROM (SELECT `question`,`question_id`,`customer_id`,`hide_my_name` FROM `oc_question` WHERE `question` LIKE'%". implode("%' or `question` LIKE '%", $keyword_tokens) . "%'".") AS t1 INNER JOIN oc_answer AS t2 ON t1.question_id = t2.question_id" ;
//	//echo $query;
//	//break;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			//var_dump($record);
//			$records[] = array('record'=>$record);
//		}
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//break;
//case 5:
//	$login = isset($_POST['login']) ? $_POST['login'] : 0;
//	try {
//		$link = getDbLink();
//		$catgories = isset($_POST['categories']) ? $_POST['categories'] : "";
//		$categoryArray = explode(',', $catgories);
//		foreach ($categoryArray as $category) {
//			$query = "insert into `oc_customer_to_category` values (". intval($login) .", ". intval($category).")" ;
//			$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//		}
//		header('Content-type: application/json');
//		echo json_encode(array('result' => 'success'));
//		closeDbLink($link);
//	} catch (Exception $e) {
//		echo json_encode(array('result' => 'failed'));
//	}
//    break;
//case 6:
//	//GetQuestionsByCategory
//	$link = getDbLink();
//	$login = isset($_POST['login']) ? $_POST['login'] : 0;
//	$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : 0;
//	$query = "select t1.question_id,t1.question,t1.customer_id,t1.hide_my_name,t2.answer_id,t2.answer FROM (SELECT `question`,`question_id`,`customer_id`,`hide_my_name` FROM `oc_question` WHERE `category_id` = ". intval($categoryid).") AS t1 INNER JOIN oc_answer AS t2 ON t1.question_id = t2.question_id" ;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			//var_dump($record);
//			$records[] = array('record'=>$record);
//		}
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//case 7:
//	/*
//	*	Output:
//	*		1.QuestionId
//	*	Input:
//	*		1.cat_id AS categoryid
//	*		2.cat_name AS categoryname
//	*		3.question
//	*		4.option(as an array)
//	*		5.userid
//	*		6.who_can_see, <default-0;friends-1>
//	*		7.who_can_answer, <default-0;friends-1>
//	*		8.days_to_decide(num_of_days),
//	*		9.show_my_name(YES/NO) <hide_my_name; 0 or 1>,
//	*		10.default_chart
//	*/
//	$link = getDbLink();
//	try{
//		begin($link);
//		$userid = isset($_POST['userid']) ? $_POST['userid'] : 0;
//		$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : 0;
//		$categoryname = isset($_POST['categoryname']) ? $_POST['categoryname'] : 0;
//		$question = isset($_POST['question']) ? $_POST['question'] : 0;
//		$option = isset($_POST['option']) ? $_POST['option'] : 0;
//		$optionArray = explode(',', $option);
//		$whocansee = isset($_POST['whocansee']) ? $_POST['whocansee'] : 0;
//		$whocananswer = isset($_POST['whocananswer']) ? $_POST['whocananswer'] : 0;
//		$daystodecide = isset($_POST['daystodecide']) ? $_POST['daystodecide'] : 365;
//		$showmyname = isset($_POST['daystodecide']) ? $_POST['daystodecide'] : 0;
//		$hidemyname = $showmyname == 1 ? 0 : 1;
//		//insert values into the question database
//		$query = "INSERT INTO `oc_question`(`customer_id`, `category_id`, `group_id`, `question`, `email_sent`, `who_can_see`, `who_can_answer`, `hide_my_name`, `showmultiplegraph`,`urgency_day`) VALUES (".intval($userid).",".intval($categoryid).",0,'".$question."',0,".intval($whocansee).",".intval($whocananswer).",".intval($hidemyname).",0,".intval($daystodecide).")" ;
//		mysql_query($query,$link);
//		$questionId = mysql_insert_id();
//		//insert options in the answers database
//		for($i = 0; $i < count($optionArray); ++$i) {
//			$query = "INSERT INTO `oc_answer`( `question_id`, `answer`) VALUES (". intval($questionId) .", '". $optionArray[$i]."')" ;
//			$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//		}
//		commit($link);
//		echo json_encode(array('result' => 'success', "questionId"=> $questionId));
//	} catch (Exception $e) {
//		rollback($link);
//		echo json_encode(array('result' => 'failed'));
//	}
//	closeDbLink($link);
//	break;
//case 8:
//	//PostVoteforQuestion
//	//voter_id,question_user_id,question_id,answer_id,check_vote,vote_date,visited,decision_visited
//	//questionid,userid,vote(option)
//	$link = getDbLink();
//	$login = isset($_POST['login']) ? $_POST['login'] : 0;
//	$questionVoterId = isset($_POST['questionvoterid']) ? $_POST['questionvoterid'] : "";
//	$questionId = isset($_POST['questionid']) ? $_POST['questionid'] : "";
//	$answerId = isset($_POST['answerid']) ? $_POST['answerid'] : "";
//
//	$query = "select `check_vote` from `oc_voting` where`voter_id`='".$login."' and `question_id`='".$questionId."'";
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//
//	if(mysql_num_rows($result)){
//		$resultarray =  mysql_fetch_assoc($result);
//		$checkVote = $resultarray['check_vote'];
//		$votesBalance = 4 - intval($checkVote);
//		if($votesBalance > 0){
//
//			$SQL = " UPDATE oc_voting SET ";
//			$SQL.= " answer_id = '" . $answerId . "',";
//			$SQL.= " check_vote = '". ++$checkVote ."',";
//			$SQL.= " vote_date = NOW() ";
//			$SQL.= " WHERE voter_id = '" .intval($login) . "'" ;
//			$SQL.= " AND question_id = '" . intval($questionId) . "'";
//
//			mysql_query($SQL,$link) or die('Errant query:  '.$SQL);
//
//			$SQL = " UPDATE oc_question SET ";
//			$SQL.= " recent_activity_date = NOW()";
//			$SQL.= " WHERE question_id = '" . $questionId. "'";
//
//			mysql_query($SQL,$link) or die('Errant query:  '.$SQL);
//
//			echo json_encode(array('result' => 'success','remainingvotes' => $votesBalance - 1,'message' => 'vote updated'));
//		}else{
//			echo json_encode(array('result' => 'failure','remainingvotes' => $votesBalance - 1,'message' => 'max votes allowed on a question is 4'));
//		}
//	}else{
//		//add
//		$SQL = " INSERT INTO oc_voting SET ";
//		$SQL.= " voter_id = '" . intval($login) . "',";
//		$SQL.= " question_user_id = '" . intval($questionVoterId) . "',";
//		$SQL.= " question_id = '" . intval($questionId) . "',";
//		$SQL.= " answer_id = '" . intval($answerId) . "',";
//		$SQL.= " check_vote = '1',";
//		$SQL.= " vote_date = NOW() ";
//
//		mysql_query($SQL,$link) or die('Errant query:  '.$SQL);
//
//
//		$SQL = " UPDATE oc_question SET ";
//		$SQL.= " recent_activity_date = NOW()";
//		$SQL.= " WHERE question_id = '" . $questionId. "'";
//
//		mysql_query($SQL,$link) or die('Errant query:  '.$SQL);
//		echo json_encode(array('result' => 'success','remainingvotes' => '3','message' => 'vote added'));
//	}
//	closeDbLink($link);
//	break;
//case 10:
//	/*
//	*	Output:
//	*  		1.Decision pending count
//	*		2.Decision accepted count
//	*		3.Decision rejected count
//	*	Input:
//	*		1.UserId
//	*/
//	try {
//		$link = getDbLink();
//		$userid = isset($_POST['userid']) ? $_POST['userid'] : 0;
//		//Get the vote count for the respective userid
//		$query1 = "SELECT COUNT(DISTINCT  `question_id` ,  `answer_id`) AS `count`  FROM  `oc_voting` WHERE  `voter_id` =". intval($userid);
//		$result1 = mysql_query($query1,$link);
//		$result1array =  mysql_fetch_assoc($result1);
//		$totalVotes = $result1array["count"];
//		//Get the questions that have been answered out of the previous list
//		$query2 = "SELECT  COUNT(*) AS `count` FROM (SELECT DISTINCT  `question_id` ,  `answer_id`  FROM  `oc_voting` WHERE  `voter_id` =". intval($userid) .") AS t1 INNER JOIN oc_decision AS t2 ON t1.question_id = t2.question_id";
//		$result2 = mysql_query($query2,$link);
//		$result2array =  mysql_fetch_assoc($result2);
//		$closedQuestions = $result2array["count"];
//		//Get the questions that have been answered correctly
//		$query3 = "SELECT  COUNT(*) AS `count` FROM (SELECT DISTINCT  `question_id` ,  `answer_id`  FROM  `oc_voting` WHERE  `voter_id` =". intval($userid) .") AS t1 INNER JOIN oc_decision AS t2 ON t1.question_id = t2.question_id AND t1.answer_id = t2.answer_id";
//		$result3 = mysql_query($query3,$link);
//		$result3array =  mysql_fetch_assoc($result3);
//		$hitQuestions = $result3array["count"];
//
//		header('Content-type: application/json');
//		echo json_encode(array('result' => 'success','decisionPending' => intval($totalVotes) - intval($closedQuestions), 'decisionAccepted' => intval($hitQuestions) , 'decisionRejected' =>   intval($closedQuestions) - intval($hitQuestions)));
//		closeDbLink($link);
//	} catch (Exception $e) {
//		echo json_encode(array('result' => 'failed'));
//	}
//	break;
//case 11:
//	//GetCountryList[o/p country names & country codes]
//	$link = getDbLink();
//	$query = "select `country_id`, `name` from `oc_country`" ;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			//var_dump($record);
//			$records[] = array('record'=>$record);
//		}
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//case 12:
//	//GetRegionList [i/p country code ; o/p region names & region codes]
//	$link = getDbLink();
//	$countryid = isset($_POST['countryid']) ? intval($_POST['countryid']) : 0;
//	$query = 'select `zone_id`, `name` from `oc_zone` where `country_id` =' .$countryid ;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			$records[] = array('record'=>$record);
//		}
//	}else{
//		$record  = array(
//			"zone_id" => 0,
//			"name" => "--",
//		);
//		$records[] = array('record'=>$record);
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//case 13:
//	//GetQuestionDetails
//	$link = getDbLink();
//	$questionid = isset($_POST['questionid']) ? $_POST['questionid'] : 0;
//	$query = "SELECT a1.question_id,a1.question,a1.answer_id,a1.answer, COUNT(a2.answer_id)AS votes FROM (SELECT t1.question_id,t1.question,t2.answer_id,t2.answer from (SELECT `question_id`, `question` FROM `oc_question` WHERE `question_id` = ".intval($questionid).") AS t1 INNER JOIN `oc_answer` AS t2 on  t1.question_id = ".intval($questionid)." AND t1.question_id = t2.question_id) AS a1 left join (SELECT `vote_id`,`answer_id` FROM `oc_voting` WHERE `question_id` = ".intval($questionid).") AS a2 on a1.answer_id = a2.answer_id GROUP BY a2.answer_id" ;
//	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
//	$records = array();
//	if(mysql_num_rows($result)) {
//		while($record = mysql_fetch_assoc($result)) {
//			//var_dump($record);
//			$records[] = array('record'=>$record);
//		}
//	}
//	header('Content-type: application/json');
//	echo json_encode(array('records'=>$records));
//	closeDbLink($link);
//	break;
//default:
//	echo json_encode(array('result' => 'failed'));
//}
//
///* disconnect from the db */
?>